package com.yonyou.service;

import com.yonyou.iuap.print.client.utils.HttpTookit;
import com.yonyou.print.aop.LogUtil;
import com.yonyou.print.params.ParamsEngine;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.Map;

/**
 * 发起请求与获取AccessToken凭证类
 *
 * @author wangjwm
 * @date 2016年8月1日 上午10:48:48
 */
@Service("httpService")
public class HttpService {
    /**
     * 发送Post请求
     *
     * @param url   云服务地址
     * @param param 参数
     * @return
     */
    public  Object httpPostRequest(String url,Map<String, String> param) {
        //log参数

        LogUtil.aopLog("url="+url+ "param="+param.toString());
        String print_token =  ParamsEngine.getInfoConfig().getProperty("print_token");
        String tenantId = ParamsEngine.getInfoConfig().getProperty("tenantId");
        param.put("print_token",print_token);
        param.put("tenantId",tenantId);
        param.put("url",url);


        String serviceUrl = ParamsEngine.getInfoConfig().getProperty("serviceUrl");
        serviceUrl = "http://"+serviceUrl+"/print_service/print/dopost";
        Object result = HttpTookit.doPost(serviceUrl,param);

        //log结果
        String logInfo = null == result?"结果空!":result.toString();
        LogUtil.aopLog("result="+logInfo.substring(0,logInfo.length()>128?128:logInfo.length()-1));
        return result;
    }

    /**
     * 发送Get请求
     *
     * @param url   云服务地址
     * @param param 参数
     * @return
     */
    public  Object httpGetRequest(String url,Map<String, String> param) {
        //log参数
        LogUtil.aopLog("url="+url+ "    param="+param.toString());

        String print_token =  ParamsEngine.getInfoConfig().getProperty("print_token");
        String tenantId = ParamsEngine.getInfoConfig().getProperty("tenantId");
        param.put("print_token",print_token);
        param.put("tenantId",tenantId);
        param.put("url",url);


        String serviceUrl = ParamsEngine.getInfoConfig().getProperty("serviceUrl");
        serviceUrl ="http://"+ serviceUrl+"/print_service/print/doget";

        Object result = HttpTookit.doGet(serviceUrl,param,null,null);

        //log结果
        if(null == result){
            return "结果空";
        }
        String logInfo = null == result?"结果空!":result.toString();
        LogUtil.aopLog("result="+logInfo.substring(0,logInfo.length()>128?128:logInfo.length()-1));
        return result;
    }



    /**
     * 处理post,get的结果
     * @param response
     */
    public  void handResult(HttpServletResponse response,Object result){
        try{
            PrintWriter write =  response.getWriter();
            if(null == result){
                write.write("error:未返回结果!");
                return;
            }
            write.write(result.toString());
        }catch (Exception e){
            LogUtil.exceptionLog(e.getMessage(),e);
        }
    }

}























